package wf3.servlet;

import acceso.servlet.Conpar;
import acceso.servlet.Regist;
import wf.dto.ContenedorDto;
import acceso.util.Escritor;
import acceso.util.UserSesion;
import acceso.util.WorkflowUtil;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import wf3.core.dao.WorkflowDAO;
import wf3.core.manager.DAOFactory;
import wf3.util.EmptyContenedorDto;

public class WorkflowServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        super.init();
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        long ini = System.currentTimeMillis();
        response.setContentType("text/html;charset=ISO-8859-1");
        Escritor.escribe_debug(" Iniciando Workflow 2.1 =>" + request.getContextPath() + " " + request.getQueryString());
        HttpSession session = request.getSession();
        UserSesion US = (UserSesion) session.getAttribute("US");
        ContenedorDto contenedor = (ContenedorDto) request.getAttribute("cnt");
        WorkflowDAO dao = (WorkflowDAO) DAOFactory.get_workflowdao(US.getId_sesion());

        try {
            long id_frawor = dao.getIdFrawor();
            long id_fraant = WorkflowUtil.convertir_long(request.getParameter("id_fraant"), 0L);
            int co_conpad = WorkflowUtil.convertir_entero(request.getParameter("co_conpad"), -1);

            contenedor.setCabecera(WorkflowUtil.convertir_boolean(request.getParameter("cabecera"), true));
            contenedor.setNo_item(WorkflowUtil.validar_string(request.getParameter("item"), ""));
            contenedor.setNo_path(WorkflowUtil.validar_string(request.getParameter("path"), ""));
            contenedor.setTransa(dao.getTransaIni(request.getRemoteHost(), WorkflowUtil.convertir_fecha(request.getParameter("fe_solini"), null)));

            dao.joindTransa_IdFrawor(id_frawor, id_fraant, contenedor.getCo_conten());

            List<Regist> l_regist = WorkflowUtil.conseguir_regist(request, "va_regist_");
            if (!l_regist.isEmpty()) {
                dao.deletePagreg(id_fraant, ((Regist) l_regist.get(0)).getPagina());
                l_regist.stream().forEach((r) -> {
                    dao.insertPagreg(id_fraant, r);
                });
            }

            List<Conpar> ls_conpar = WorkflowUtil.conseguir_conpar(request, "co_conpar");

            ls_conpar.stream().forEach(c -> dao.insertConpar(id_frawor, contenedor.getCo_conten(), c));
            contenedor.setUrl("co_conten=" + contenedor.getCo_conten() + "&" + String.join("&", ls_conpar.stream().map(c -> "co_conpar_" + c.getId() + "=" + c.getValor()).collect(Collectors.toList())));

            //INICIA TRACONINI
            dao.insertTraconini(contenedor.getTransa(), id_frawor, contenedor.getCo_conten());

            contenedor.setPaginas(dao.getConpag(contenedor.getCo_conten(), id_frawor));
            if (contenedor.getPaginas().size() > 0) {
                contenedor.setTabs(dao.getContab(contenedor.getCo_conten()));
            } else {
                throw new IOException("No existen paginas para este contenedor co_conten=" + contenedor.getCo_conten());
            }

            contenedor.setCo_conpad(co_conpad);
            session.setAttribute("c" + id_frawor, contenedor);
            DAOFactory.closedao(dao);

            if (WorkflowUtil.convertir_boolean(request.getParameter("popup"))) {
                RequestDispatcher dispatcher = request.getRequestDispatcher("/workflow2/contenedorbody.jsp?id_frawor=" + id_frawor);
                dispatcher.forward(request, response);
            } else {
                if (contenedor.isCabecera()) {
                    RequestDispatcher dispatcher = request.getRequestDispatcher("/workflow2/contenedor.jsp?id_frawor=" + id_frawor);
                    dispatcher.forward(request, response);
                } else {
                    RequestDispatcher dispatcher = request.getRequestDispatcher("/workflow2/contenedorbody.jsp?id_frawor=" + id_frawor);
                    dispatcher.forward(request, response);
                }
            }
        } catch (Exception ep) {
//        } catch (ServletException | IOException ep) {
            DAOFactory.closedao(dao);
            if (!(contenedor instanceof EmptyContenedorDto)) {
                EmptyContenedorDto cnt = new EmptyContenedorDto();
                cnt.setCo_conten(-1);
                cnt.addException(ep);
                session.setAttribute("c0", cnt);
            } else {
                contenedor.addException(ep);
                session.setAttribute("c0", contenedor);
            }
            RequestDispatcher dispatcher = request.getRequestDispatcher("/workflow2/contenedor.jsp?id_frawor=" + 0);
            dispatcher.forward(request, response);
        }
        Escritor.escribe_debug("[" + US.getId_sesion() + "] [WorkflowServlet " + (System.currentTimeMillis() - ini) + "ms]");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Servlet WF2";
    }
}
